// 根据当前项目情况重新配置 axios
import axios from 'axios'
import router from '../router'
//import qs from 'qs'

// 创建 axios 实例
const instance = axios.create({
  // baseURL: '/api',
  baseURL: 'http://172.16.14.81:8080',
  timeout: 1000 // 请求超时，超过这个时间请求没有返回则请求失败
})
  
// 请求拦截
instance.interceptors.request.use((config) => {

  // if (config.method === "post") { // 这一步主要取决于后端是否可以接受 json
  //       config.headers = {
  //         'Content-Type':'application/x-www-form-urlencoded'
  //       }
  //       // 参数序列化
  //       config.data = qs.stringify(config.data);
  //     }

  // Do something before request is sent
  // 统一在请求头携带 token
 
  const token = localStorage.getItem('token')
  // token && (config.headers['Authorization'] = 'Bearer ' + token)
  token && (config.headers['Authorization'] =  token)


  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

// 响应拦截
instance.interceptors.response.use((response) => {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data

  // 如果后端返回最新的token则更新本地 token
  if (response.data.token) {
    localStorage.setItem('token', response.data.token)
  }

  return response;
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error

  const _response = error.response

  switch (_response.status) { // 判断 HTTP 状态码
    case 401:
      // token 验证失败
      localStorage.removeItem('token')
      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath // 跳转之前，将原本想访问的路径保存在 query
        }
      })
      break

    case 404:
      console.log('资源不存在')
      break

    case 408:
      console.log('请求超时了')
      break
    case 500:
      console.log('服务器错误')
      Promise.reject(error)
      break
  }

  return Promise.reject(error);
})

export default instance


//请求队列, 同个请求被触发多次合并

//取消请求,调到下个页面后怎么取消请求